package com.lekang.system.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lekang.common.utils.DateUtils;
import com.lekang.common.utils.SecurityUtils;
import com.lekang.system.domain.AccraditationRecord;
import com.lekang.system.domain.PendingTasks;
import com.lekang.system.mapper.AccraditationRecordMapper;
import com.lekang.system.service.IAccraditationRecordService;
import com.lekang.system.service.IElderlyService;
import com.lekang.system.service.IPendingTasksService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lekang.system.mapper.LeaveRequestMapper;
import com.lekang.system.domain.LeaveRequest;
import com.lekang.system.service.ILeaveRequestService;

/**
 * 请假Service业务层处理
 *
 * @author zhihao
 * @date 2025-10-14
 */
@Service
public class LeaveRequestServiceImpl implements ILeaveRequestService
{
    @Autowired
    private LeaveRequestMapper leaveRequestMapper;

    /**
     * 查询请假
     *
     * @param id 请假主键
     * @return 请假
     */
    @Override
    public LeaveRequest selectLeaveRequestById(Long id)
    {
        return leaveRequestMapper.selectLeaveRequestById(id);
    }



    /**
     * 查询请假列表
     *
     * @param leaveRequest 请假
     * @return 请假
     */
    @Override
    public List<LeaveRequest> selectLeaveRequestList(LeaveRequest leaveRequest)
    {
        return leaveRequestMapper.selectLeaveRequestList(leaveRequest);
    }

    /**
     * 新增请假
     *
     * @param leaveRequest 请假
     * @return 结果
     */
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IAccraditationRecordService accraditationRecordService;
    @Autowired
    private AccraditationRecordMapper accraditationRecordMapper;
    @Autowired
    private IPendingTasksService pendingTasksService;
    @Autowired
    private IElderlyService elderlyService; // 用于查询老人信息
    @Override
    public int insertLeaveRequest(LeaveRequest leaveRequest)
    {
        //1.校验：检查该老人是否可以提交新的请假申请
        System.out.println("=== 开始校验请假申请 ===");
        if (leaveRequest.getElderlyId() != null) {
            // 查询该老人的最新请假记录
            LeaveRequest queryParam = new LeaveRequest();
            queryParam.setElderlyId(leaveRequest.getElderlyId());
            List<LeaveRequest> existingRequests = leaveRequestMapper.selectLeaveRequestList(queryParam);
            
            if (existingRequests != null && !existingRequests.isEmpty()) {
                // 获取最新的请假记录（按ID降序，第一条就是最新的）
                LeaveRequest latestRequest = existingRequests.get(0);
                String status = latestRequest.getLeaveStatus();
                
                System.out.println("老人ID: " + leaveRequest.getElderlyId() + " 的最新请假状态: [" + status + "]");
                System.out.println("状态值类型: " + (status != null ? status.getClass().getName() : "null"));
                System.out.println("状态值长度: " + (status != null ? status.length() : "0"));
                
                // 数据字典定义：
                // "0" - 超时未归
                // "1" - 已返回 (允许)
                // "2" - 请假中 (不允许)
                // "3" - 审批中 (不允许)
                boolean canApply = false;
                String statusText = "";
                
                if (status == null || status.trim().isEmpty()) {
                    canApply = true;
                    System.out.println("状态为空，允许申请");
                } else {
                    String trimmedStatus = status.trim();
                    
                    // 只有状态为"1"（已返回）时才允许提交新申请
                    if ("1".equals(trimmedStatus)) {
                        canApply = true;
                        statusText = "已返回";
                        System.out.println("状态匹配：1 - 已返回，允许申请");
                    } else if ("0".equals(trimmedStatus)) {
                        canApply = false;
                        statusText = "超时未归";
                        System.out.println("状态为：0 - 超时未归，不允许申请");
                    } else if ("2".equals(trimmedStatus)) {
                        canApply = false;
                        statusText = "请假中";
                        System.out.println("状态为：2 - 请假中，不允许申请");
                    } else if ("3".equals(trimmedStatus)) {
                        canApply = false;
                        statusText = "审批中";
                        System.out.println("状态为：3 - 审批中，不允许申请");
                    } else {
                        canApply = false;
                        statusText = trimmedStatus;
                        System.out.println("未知状态：" + trimmedStatus + "，不允许申请");
                    }
                }
                
                if (!canApply) {
                    String errorMsg = statusText.isEmpty() ? 
                        "该老人当前状态码为【" + status + "】，无法提交新的请假申请" :
                        "该老人当前状态为【" + statusText + "】，无法提交新的请假申请";
                    System.out.println("校验失败：" + errorMsg);
                    throw new RuntimeException(errorMsg);
                }
                
                System.out.println("校验通过：该老人当前状态为【" + (statusText.isEmpty() ? status : statusText) + "】，可以提交新的请假申请");
            } else {
                System.out.println("该老人没有请假记录，可以提交新的请假申请");
            }
        }
        
        // 2.保存请假信息
        System.out.println("=== 开始保存请假申请 ===");
        System.out.println("前端传入的leaveStatus: " + leaveRequest.getLeaveStatus());
        leaveRequest.setCreateTime(DateUtils.getNowDate());
        //使用security中的工具类来获取
        Long userId = SecurityUtils.getUserId();
        leaveRequest.setCreator(userId);//设置创建人
        int num= leaveRequestMapper.insertLeaveRequest(leaveRequest);
        System.out.println("保存后的ID: " + leaveRequest.getId());
        System.out.println("=== 请假申请保存完成 ===");
        // 3.设置节点办理人信息
        Map map = new HashMap();
        map.put("assignee1",userId);
        long hlzId=101L;
        map.put("assignee2",hlzId);
        // 4.创建流程实例绑定businessKey
        runtimeService.startProcessInstanceByKey("qingjia",leaveRequest.getId().toString() ,map);
        // 5.完成节点
        Task task = taskService.createTaskQuery()
                .processInstanceBusinessKey(leaveRequest.getId().toString())
                .processDefinitionKey("qingjia")
                .taskAssignee(userId.toString())
                .singleResult();
        if(task!=null){
            taskService.complete(task.getId());
        }
        
        // 6.查询老人姓名，用于待办任务标题
        String elderlyName = "未知老人";
        if (leaveRequest.getElderlyId() != null) {
            com.lekang.system.domain.Elderly elderly = elderlyService.selectElderlyById(leaveRequest.getElderlyId());
            if (elderly != null && elderly.getName() != null) {
                elderlyName = elderly.getName();
            }
        }
        
        // 7.查询工作流下一个任务节点id（先查询，以便保存到审批记录中）
        Task nextTask = taskService.createTaskQuery()
                .processInstanceBusinessKey(leaveRequest.getId().toString())
                .processDefinitionKey("qingjia")
                .taskAssignee(String.valueOf(hlzId)).singleResult();
        
        String nextTaskId = null;
        if (nextTask != null) {
            nextTaskId = nextTask.getId();
            System.out.println("查询到下一个任务ID: " + nextTaskId);
        } else {
            System.out.println("警告：未查询到下一个任务节点");
        }
        
        // 8.保存审批记录（首提记录，护理员发起申请）
        AccraditationRecord record = new AccraditationRecord();
        record.setOpinion("发起请假申请");
        record.setType(2L);
        record.setFinishTime(new Date());
        record.setCreateTime(new Date());
        record.setApproverId(userId);
        record.setApproverName(SecurityUtils.getUsername());
        record.setApproverNameRole("护理员");
        record.setNextApproverId(hlzId);
        record.setNextApprover("护理组长");
        record.setNextApproverRole("组长");
        record.setBussniessId(leaveRequest.getId());
        record.setCurrentStep("发起申请-申请请假");
        record.setNextStep("审批-申请审批");
        record.setAuditStatus(1L);  // 1表示通过（护理员提交申请）
        record.setStepNo(1L);
        record.setHandleType(1L);
        record.setExtraField1(nextTaskId);  // 保存下一个任务的taskId
        // 直接调用mapper插入，避免调用service中的complete逻辑
        accraditationRecordMapper.insertAccraditationRecord(record);
        System.out.println("审批记录已保存，包含nextTaskId: " + nextTaskId);

        // 9.保存我的申请（护理员的申请记录，已完成状态，不需要taskId）
        PendingTasks pendingTasks = new PendingTasks();
        pendingTasks.setBussniessId(leaveRequest.getId());
        // 护理员的申请已完成，不需要保存taskId
        // pendingTasks.setTaskId() - 留空
        pendingTasks.setTitle(elderlyName + "的请假申请");
        pendingTasks.setType(2L);
        pendingTasks.setAssignee(SecurityUtils.getUsername());
        pendingTasks.setAssigneeId(userId);
        pendingTasks.setStatus(1L);
        pendingTasks.setApplicationTime(leaveRequest.getCreateTime());
        pendingTasks.setApplicat(SecurityUtils.getUsername());
        pendingTasks.setApplicatId(userId);
        pendingTasks.setFinishTime(new Date());
        pendingTasks.setIsHandle(1L);  // 1表示已处理
        pendingTasks.setStepNo(1L);
        pendingTasksService.insertPendingTasks(pendingTasks);
        
        // 10.保存我的待办任务 -- 下一个人的待办任务
        PendingTasks pt = new PendingTasks();
        pt.setBussniessId(leaveRequest.getId());
        if (nextTask != null) {
            pt.setTaskId(nextTask.getId());
        }
        pt.setTitle(elderlyName + "的请假申请");
        pt.setType(2L);
        pt.setAssignee(record.getNextApprover());
        pt.setAssigneeId(record.getNextApproverId());
        pt.setStatus(1L);
        pt.setApplicationTime(leaveRequest.getCreateTime());
        pt.setApplicat(SecurityUtils.getUsername());
        pt.setApplicatId(userId);
        pt.setIsHandle(0L);
        pt.setStepNo(2L);
        pendingTasksService.insertPendingTasks(pt);
        return num;

    }

    /**
     * 修改请假
     *
     * @param leaveRequest 请假
     * @return 结果
     */
    @Override
    public int updateLeaveRequest(LeaveRequest leaveRequest)
    {
        return leaveRequestMapper.updateLeaveRequest(leaveRequest);
    }

    /**
     * 批量删除请假
     *
     * @param ids 需要删除的请假主键
     * @return 结果
     */
    @Override
    public int deleteLeaveRequestByIds(Long[] ids)
    {
        return leaveRequestMapper.deleteLeaveRequestByIds(ids);
    }

    /**
     * 删除请假信息
     *
     * @param id 请假主键
     * @return 结果
     */
    @Override
    public int deleteLeaveRequestById(Long id)
    {
        return leaveRequestMapper.deleteLeaveRequestById(id);
    }
}
